package com.xx.servlet.model;

import com.xx.bean.Book;
import com.xx.service.BookService;
import com.xx.service.impl.BookServiceImpl;
import com.xx.servlet.base.ModelBaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class BookManagerServlet extends ModelBaseServlet {
    private BookService bookService = new BookServiceImpl();

    /**
     * 跳转到图书管理页面
     */
    public void toBookManagerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 查出所以的图书数据
        List list = bookService.selectBooks();
        // 放入请求域中
        request.setAttribute("list",list);
        processTemplate("manager/book_manager", request, response);
    }

    /**
     * 删除图书 根据id
     * */
    public void removeBook(HttpServletRequest request,HttpServletResponse response){
        Integer parameter = Integer.valueOf(request.getParameter("id"));
        try {
            bookService.removeBookById(parameter);
            response.sendRedirect(request.getContextPath()+"/bookManager?method=toBookManagerPage");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 去添加图书页面
     * */
    public void toAddPage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        processTemplate("manager/book_edit",request,response);
    }
    /**
     * 添加或者修改图书
     * */
    public void addorupdateBook(HttpServletRequest request,HttpServletResponse response)throws Exception{
        Map<String, String[]> map = request.getParameterMap();
        Book book = new Book();
        BeanUtils.populate(book,map);
        if (book.getBookId() != null && !"".equals(book.getBookId())){
            //修改图书
            bookService.updateBook(book);
        }else {
            //添加图书
            book.setImgPath("static/uploads/xiaowangzi.jpg");
            bookService.addBook(book);
        }


        response.sendRedirect(request.getContextPath()+"/bookManager?method=toBookManagerPage");
    }

    /**
     * 跳转到修改图书页面
     * */
    public void toEditPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        try {
            Book book = bookService.getBookById(id);
            request.setAttribute("book",book);
        }catch (Exception e){
            e.printStackTrace();
        }
        processTemplate("manager/book_edit", request, response);
    }
}
